//studentsController 用于处理students集合的业务逻辑：
//引入集合模型
const { studentsModel } = require("../models/studentsModel");


//获取所有数据
// async function getAllStudents (req, res, next) {
//     let students = await studentsModel.find({}).populate({
//       path: 'classId',
//       populate:{
//         path:"tid"
//       }
//     });
//     res.send({code:1, students });
// }

// skip（）limit函数的时候要求必须传递number类型
async function getAllStudents (req, res, next) {
  const {pageNum,pageSize} = req.query
  console.log(pageNum,pageSize);
  // 获取到当前查询的文档所有的总条数
  const total = await studentsModel.countDocuments()
  // 计算一共多少页
  const pages = Math.ceil(total/pageSize)
  console.log(total);
  let students = await studentsModel.find({}).populate({
    path: 'classId',
    populate:{
      path:"tid"
    }
  }).skip((pageNum-1)*pageSize).limit(parseInt(pageSize));
  res.send({
    code:1, 
    students,
    total ,
    pages
  });
}
// 获取所有的学生，分页
// async function getAllStudents(req, res, next) {
//   const { pageNum, pageSize } = req.query
//   console.log(pageNum, pageSize);
//   // 获取所有的页码
//   const total = await studentsModel.countDocuments()
//   // 计算一共多少页
//   const pages = Math.ceil(total / pageSize)
//   let students = await studentsModel.find({}).populate({
//     path: 'classId',
//     populate: {
//       path: "tid"
//     }
//   }).skip((pageNum - 1) * pageSize).limit(parseInt(pageSize));
//   // 响应内容回客户端
//   res.send(
//     {
//       code: 1,
//       students,
//       total,
//       pages
//     });
// }

//获取指定_id的数据
async function getStudentById(req, res, next) {
  let { _id } = req.params;
  let students = await studentsModel.find({ _id });
  res.send({ student: students[0] });
}
//新增数据
async function addStudent(req, res, next) {
  let result = await studentsModel.create(req.body);
  if (result) {
    res.send({ "message": "新增成功", code: 200 })
  } else {
    res.send({ "message": "新增失败", code: -1 })
  }
}
//更新
async function updateStudents(req, res, next) {
  let result = await studentsModel.updateMany({ _id: req.body._id }, req.body);
  if (result.modifiedCount > 0) {
    res.send({ message: "修改成功", code: 200 })
  } else {
    res.send({ message: "修改失败", code: -1 })
  }
}
//查询
async function searchStudents(req, res, next) {
  let { key, value } = req.body;
  let obj = {};
  //模拟匹配
  if (key == "age") {
    obj[key] = value
  } else {
    obj[key] = { $regex: value, $options: "$i" };
  }
  let students = await studentsModel.find(obj).populate({
    path: 'classId',
    populate: {
      path: "tid"
    }
  });
  res.send({ students });
}


module.exports = {
  getAllStudents,
  getStudentById,
  updateStudents,
  searchStudents,
  addStudent
}